package com.peng.leetcode.tree;

import java.util.HashMap;
import java.util.Map;

/**
 * Trie
 * 208. 实现 Trie (前缀树)
 * https://leetcode.cn/problems/implement-trie-prefix-tree/
 * <p>
 * Created on 2022/12/2
 *
 * @author lupeng
 */
public class Trie {

    static class Node {
        Map<Character, Node> next = new HashMap<>();
        boolean end = false;
    }

    Node root = new Node();

    public Trie() {

    }

    public void insert(String word) {
        Node root = this.root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!root.next.containsKey(c)) {
                root.next.put(c, new Node());
            }
            root = root.next.get(c);
        }
        root.end = true;
    }

    public boolean search(String word) {
        Node root = this.root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!root.next.containsKey(c)) {
                return false;
            }
            root = root.next.get(c);
        }
        return root.end;
    }

    public boolean startsWith(String prefix) {
        Node root = this.root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (!root.next.containsKey(c)) {
                return false;
            }
            root = root.next.get(c);
        }
        return true;
    }

}
